import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserProfile, getUserDetailById, } from "@/api/user";

export default {
    namespaced: true,
    state: {
        token: getToken() || '',
        userInfo: {}
    },
    mutations: {
        updateToken(state, token) {
            state.token = token
            setToken(token)
        },
        removeToken(state) {
            state.token = ''
            removeToken()
        },
        updateUserInfo(state, info) {
            state.userInfo = info
        },
        removeUserInfo(state) {
            state.userInfo = {}
        }
    },
    actions: {
        async userLogin(context, loginForm) {
            const res = await login(loginForm);
            console.log("res login", res);
            context.commit('updateToken', res.data)
        },
        async getUserInfo(context) {
            try {
                const res = await getUserProfile()
                console.log('getUserProfile', res);
                const info = await getUserDetailById(res.data.userId)
                console.log('getUserDetailById', info);
                context.commit('updateUserInfo', {...res.data, ...info.data })
            } catch (error) {
                console.log('error', error);
            }
        },
        logout(context) {
            context.commit('removeToken')
            context.commit('removeUserInfo')
        }
    },
};